{% extends 'layout/manage.html' %}
{% block css %}
    <style>
        .panel-default .panel-heading {
            display: flex;
            flex-direction: row; /* 按照行布局*/
            justify-content: space-between; /* 左右排列*/
        }

        .panel-default > .panel-heading a {
            text-decoration: none;
        }

        .panel-default > .panel-heading span {
            padding: 0 5px;
        }

        .panel-default > .panel-heading .function .upload {
            overflow: hidden;
        }

        .panel-default > .panel-heading .function .upload input {
            opacity: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            width: 76px;
            left: -2px;
            overflow: hidden;
        }

        .upload-progress {
            position: fixed;
            right: 2px;
            bottom: 2px;
            width: 400px;

        }
        .upload-progress .progress-error {
            color: red;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="bs-example" data-example-id="table-within-panel" style="padding-left: 10px; padding-right: 10px">
        <div class="panel panel-default">
            <!-- Default panel contents -->
            <div class="panel-heading">
                <div>
                    <a href="{% url 'file' request.obj.0.0 %}"><i class="fa fa-home" aria-hidden="true"></i>文件库</a>
                    {% for i in breadcrumb_list %}
                        <a href="{% url 'file' request.obj.0.0 %}?folder={{ i.id }}"> &nbsp;&nbsp;<i class="fa fa-share" aria-hidden="true"></i> &nbsp;&nbsp;{{ i.name }}</a>
                    {% endfor %}

                </div>
                <div class="function">
                    <div class="btn btn-primary btn-xs upload" style="position: relative">
                        <div><i class="fa fa-upload" aria-hidden="true"></i>上传文件</div>
                        <input type="file" multiple name="uploadFile" id="uploadFile">
                    </div>
                    <!--data-toggle="modal" data-target="#addMode" 相当于这个a标签绑定了一个事件  -->
                    <a class="btn btn-success btn-xs" data-toggle="modal" data-target="#addMode" data-whatever="新建文件夹"><i class="fa fa-plus-circle" aria-hidden="true"></i>新建文件夹</a>

                </div>


            </div>


            <!-- Table -->
            <table class="table">
                <thead>
                <tr>
                    <th>文件名</th>
                    <th>文件大小</th>
                    <th>Last Name</th>
                    <th>操作</th>
                    <input type="text" style="display: none" id="num">
                </tr>

                </thead>
                <tbody id="rowList">
                {% for i in file_repository %}
                    <tr>
                        <th scope="row">
                            {% if i.3 == '1' %}
                                <a href="{% url 'file' request.obj.0.0 %}?folder={{ i.0 }}">
                                    <i class="fa fa-folder" aria-hidden="true"></i>
                                    {{ i.2 }}
                                </a>

                            {% else %}
                                <i class="fa fa-file" aria-hidden="true"></i>
                                {{ i.2 }}
                            {% endif %}
                        </th>
                        <td>
                            {% if i.3 == '1' %}
                                -
                            {% else %}
                                {{ i.4 }}
                            {% endif %}
                        </td>
                        <td>Otto</td>
                        <td>
                            {% if i.3 == '1' %}
                                <a href="" class="btn btn-default btn-xs"
                                   data-toggle="modal"
                                   data-target="#addMode"
                                   data-whatever="编辑文件夹"
                                   data-name='{{ i.2 }}'
                                   data-fid="{{ i.0 }}"
                                   att="{{ i.0 }}">
                                    <i class="fa fa-pencil-square-o"></i>

                                </a>
                            {% endif %}
                            {% if i.3 == '2' %}
                                <a data_val="{{ i.7 }}" class="btn btn-default btn-xs" id="downLoad" href="{% url 'file_download' request.obj.0.0 i.0 %}">
                                    <i class="fa fa-cloud-download fa-lg" aria-hidden="true"></i>
                                </a>
                            {% endif %}
                            <a href="" class="btn btn-danger btn-xs "
                               data-target="#alertMode"
                               data-toggle="modal"
                               att="{{ i.0 }}">
                                <i class="fa fa-trash"></i>
                            </a>

                        </td>
                    </tr>
                {% endfor %}

                </tbody>
            </table>
        </div>

        <div class="modal fade" tabindex="-1" role="dialog" id="addMode">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title"></h4>
                    </div>
                    <div class="modal-body">
                        <form id="form">
                            {% csrf_token %}
                            <input type="text" class="hide" name="fid" id="fid">
                            {% for i in form %}
                                <div class="form-group">
                                    <label for="{{ i.id_for_label }}">{{ i.label }}</label>
                                    {{ i }}
                                    <span class="error-msg">{{ i.errors.0 }}</span>
                                </div>
                            {% endfor %}
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
                        <button type="button" class="btn btn-primary" id="btnFormSubmit">确 定</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->

        <div class="modal fade" tabindex="-1" role="dialog" id="alertMode">
            <div class="modal-dialog" role="document">
                <div class="alert alert-danger alert-dismissible fade in" role="alert">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    <h4>Oh snap! You got an error!</h4>
                    <p>内容将被删除 是否确定？</p>
                    <p style="text-align: right">
                        <a href="" class="btn btn-default btn-sm" data-dismiss="modal" aria-label="Close">取 消</a>
                        {#                        <button type="button" class="btn btn-danger" data-dismiss="model" aria-label="Close">取 消</button>#}
                        <button type="button" class="btn btn-danger" aria-label="Close" aria-hidden="true" id="btnDelete">确 定</button>
                    </p>
                </div>
            </div>
        </div>

    </div>
    {% load static %}
    <!-- 上传文件的进度条 -->
    <div id="uploadProgress" class="upload-progress hide" >
        <div class="panel panel-primary">
            <div class="panel-heading"><i class="fa fa-cloud-upload" aria-hidden="true"></i> 上传进度</div>
            <table class="table">
                <tbody class="progressList">

                </tbody>
            </table>

            <!-- Table -->
           <div class="hide">
                <table class="progressTemplate">

                    <tr>
                        <td>
                            <div class="name">视频</div>
                            <div class="progress">    <!-- 上传了几个文件 -->
                                <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                                    30%
                                </div>
                            </div>
    {#                        <div class="progress">   <!-- 每个文件的进度 -->#}
    {#                            <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 30%;">#}
    {#                                30%#}
    {#                            </div>#}
    {#                        </div>#}
                            <div class="progress-error">错误信息</div>
                        </td>
                    </tr>

            </table>
           </div>
        </div>
    </div>


    <div class="hide">
        <table id="rowTpl">
            <tr>
                <td>
                    <i class="fa fa-file" aria-hidden="true"></i>
                    <span class="name"></span>
                </td>
                <td class="file_size"></td>
                <td class="username">--</td>
                <td>

                    <a class="btn btn-default btn-xs download">
                        <i class="fa fa-cloud-download" aria-hidden="true"></i>
                    </a>

                    <a class="btn btn-danger btn-xs delete" data-toggle="modal" data-target="#alertModal">
                        <i class="fa fa-trash" aria-hidden="true"></i>
                    </a>
                </td>
            </tr>
        </table>
    </div>
{% endblock %}

{% block js %}
    <script src="{% static 'plugin/cos-js-sdk-v5-0.5.22/dist/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        /*
        *  var cos = new COS({
                SecretId: 'AKIDHI3cu67d4i6C3PzKwuc7MMhlZ6N6vw0O',
                SecretKey: 'BBvPjmZ8VdZFfspVv97tOdcNyIRK3Vhi',
            });
        *
        *
        *
        *
        * */
        var Upload_url = '{% url 'cos_credentials' request.obj.0.0 %}';
        var File_post = '{% url 'file_post' request.obj.0.0 %}';
        var FOLDER_URL = "{% url 'file' request.obj.0.0 %}";
        var File_DELETE_URL = '{% url 'file_delete' request.obj.0.0 %}';
        var father_id = '{{ father }}';
        $(function () {
            btn1();
            bindBtnFormSubmit();
            bindDeleteSubmit();
            initAddModal();
            jinggaokuang();
            bindUploadFile();

        });

        function btn1() {
            $('#addMode').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget) // Button that triggered the modal
                var recipient = button.data('whatever') // Extract info from data-* attributes
                var modal = $(this);
                var name = $(this);
                var fid = button.data('fid');
                modal.find('.modal-title').text(recipient);
                if (fid) {
                    modal.find('#id_name').val(name);
                    modal.find('#fid').val(fid)

                } else {
                    // 新建
                    modal.find('.error-msg').empty();
                    $('#form')[0].reset();
                }
            })
        }

        function bindBtnFormSubmit() {
            $('#btnFormSubmit').click(function () {
                $.ajax({
                    url: location.href,
                    type: 'post',
                    data: $('#form').serialize(),
                    dataType: 'JSON',
                    success: function (data) {
                        if (data.status) {
                            location.href = location.href;
                        } else {
                            $.each(data.error, function (key, val) {
                                $('#id_' + key).next().text(val[0])
                            })
                        }
                    }
                })
            })
        }

        function initAddModal() {
            $('#addModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget);
                var fid = button.data('fid');
                $('#btnDelete').attr('fid', fid)
            })
        }

        function bindDeleteSubmit() {
            $('#btnDelete').click(function () {
                // 获取要删除的id
                $.ajax({
                    url: File_DELETE_URL,
                    type: 'get',
                    data: {'fid': $('#num').attr('att')},
                    success: function (data) {
                        if (data.status) {
                            location.href = location.href
                        }
                    }

                })
            })
        }

        function jinggaokuang() {
            $('.table tbody td a').click(function () {
                var num = $(this).attr('att');
                console.log(num);
                $('#num').attr('att', num)
            })
        }

        function bindUploadFile() {
            //
            $('#uploadFile').change(function () {
                $('.progressList').empty()
                var fileList = $(this)[0].files;
                var checkFileList = [];
                $.each(fileList, function (index, fileObject) {
                    console.log(fileObject.name);
                    var fileName = fileObject.name;
                    checkFileList.push({'name': fileObject.name, 'size': fileObject.size})
                });
                console.log(checkFileList);
                // 把这些数据的信息发送到后台 进行校验 如果没有问题就上传 如果有问题 就显示异常信息

                var cos_credential = new COS({
                    getAuthorization: function (options, callback) {
                        $.post(Upload_url, JSON.stringify(checkFileList), function (data) {
                            if (data.status) {
                                var credentials = data.data && data.data.credentials;
                                if (!data.data || !credentials) return console.error('credentials invalid');
                                callback({
                                    TmpSecretId: credentials.tmpSecretId,
                                    TmpSecretKey: credentials.tmpSecretKey,
                                    XCosSecurityToken: credentials.sessionToken,
                                    StartTime: data.data.startTime,
                                    ExpiredTime: data.data.expiredTime,
                                });
                                $('#uploadProgress').removeClass('hide')
                                console.log(data)
                            } else {
                                alert(data.error)
                            }
                        })
                    }
                });

                // 上传之前获取秘钥(上传文件之前获取文件)
                $.each(fileList, function (index, fileObject) {
                    var fileName = fileObject.name;
                    var fileObj = fileObject;
                    var fileSize = fileObject.size;
                    var file_location = fileObject.location;
                    var key = (new Date()).getTime() + '_' + fileName
                    var tr = $('.progressTemplate').find('tr').clone();
                    tr.find('.name').text(fileName);
                    $('.progressList').append(tr);
                    //上传
                    cos_credential.putObject({
                        Bucket: '8-1302094470', /* 必须1302094470*/
                        Region: 'ap-beijing',     /* 存储桶所在地域，必须字段 */
                        Key: key,              /* 必须 */
                        //StorageClass: 'STANDARD',
                        Body: fileObj, // 上传文件对象
                        onProgress: function (progressData) {
                            {#console.log(JSON.stringify(progressData));#}
                            {#var dataDict = JSON.stringify(progressData);#}
                            console.log('这个是上传时候'+ JSON.stringify(progressData));
                            var percent = progressData.percent *100 + '%';
                            tr.find('.progress-bar').text(percent);
                            tr.find('.progress-bar').css('width', percent);
                            {#console.log('这个是陪衬他', percent, progressData)#}


                        }
                    }, function (err, data) {
                        console.log(err || data);

                        if (data && data.statusCode === 200){

                                $.post(File_post, {'name': fileName, 'key': key, 'size': fileSize, 'father': father_id, 'location': data.Location }, function (res) {
                                    if(res.status){
                                        var newTr = $('#rowTpl').find('tr').clone();
                                        newTr.find('.name').text(res.data.name);
                                        newTr.find('.file_size').text(res.data.space);
                                        newTr.find('.delete').attr('data-fid', res.data.id);
                                        newTr.find('.download').attr('href', res.data.url);
                                        $('#rowList').append(newTr);
                                        tr.remove()

                                    }
                                })
                        }else{
                            tr.find('.progress-error').text('上传失败')
                        }

                    });
                })

            })
        }


    </script>
{% endblock %}

